/*****************************************************************//**
 * \file   AnsysReaderMgr.cpp
 * \brief  AnsysReaderMgr
 *
 * \author Wyatt
 * \date   May 2023
 *********************************************************************/
#include "AnsysReaderMgr.h"
#include "AnsysAPDLReaderBase.h"
#include "AnsysDataDef.h"

#include <cassert>

ReaderMgr::ReaderMgr(void)
{}

ReaderMgr::~ReaderMgr(void)
{}

bool ReaderMgr::Read(std::string& strDataLine)
{
	return true;
}

bool ReaderMgr::Scan(std::string& strDataLine)
{
	return true;
}

ReaderMgr* ReaderMgr::_inst = nullptr;

ReaderMgr* ReaderMgr::Inst()
{
	/*static ReaderMgr singleton;
	return singleton;*/
	if (!_inst)
	{
		_inst = new ReaderMgr;
	}
	return _inst;
}

bool ReaderMgr::Regist(ReaderBase* pReader)
{
	if (!pReader) {
		//FDEBUG("Regist Reader failed.");
		assert(0);
		return false;
	}
	if (!_pCDBReader)
		_pCDBReader = pReader->GetCDBReader();
	if (_pCDBReader != pReader->GetCDBReader()) {
		//FDEBUG("Regist Reader failed. Not matched.");
		assert(0);
		return false;
	}
	ANSYS_KEYWORD keyw = pReader->GetKeyWord();
	if (keyw == KEY_UNKNOWN) {
		//FDEBUG("Regist Reader failed. Unknown key type.");
		assert(0);
		return false;
	}
	/*if (readerMap.find(keyw) != readerMap.end()) {
		//FDEBUG("Regist Reader failed. Duplicated reader type. %d", keyw);
		assert(0);
		return false;
	}*/
	readerMap[keyw] = pReader;
	readerStrMap[pReader->GetReaderName()] = keyw;

	return true;
}

ReaderBase* ReaderMgr::GetReader(ANSYS_KEYWORD keyw)
{
	auto it = readerMap.find(keyw);
	int a = readerMap.size();
	if (it == readerMap.end() || !it->second) {
		//FDEBUG("Reader not found. Key type: %d", keyw);
		//assert(0);
		return nullptr;
	}
	return it->second;
}

ANSYS_KEYWORD ReaderMgr::KeyType(std::string& keystr)
{
	auto it = readerStrMap.find(keystr);
	if (it == readerStrMap.end() || !it->second) {
		return KEY_UNKNOWN;
	}
	return it->second;
}

bool ReaderMgr::Build()
{
	for (auto it = readerMap.begin(); it != readerMap.end(); it++)
	{
		ReaderBase* pReader = it->second;
		if (pReader)
			pReader->Build();
	}
	return true;
}

bool ReaderMgr::destroy_data()
{
	if (_pCDBReader)
	{
		_pCDBReader = nullptr;
		delete _pCDBReader;
	}
	if (_inst)
	{
		delete _inst;
		_inst = nullptr;
	}
	/*for (auto&i: readerMap)
	{
		if (i.second)
		{
			i.second->destroy_instance();
			i.second = nullptr;
		}
	}*/
	//delete readerMap.begin()->second;
	//readerMap.clear();
	//readerStrMap.clear();
	

	return true;
}
